package com.example.mychat;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * @Description
 * @Author susu
 * @Date 2024/9/3
 */
public class testSocketServer {

    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(1024);
        Map<String,Socket> CLENT_MAP = new HashMap<>();
        System.out.println("服务已启动,等待客户端连接");


        while (true) {
            //等客户端连接 不然一直卡着
            Socket socket = server.accept();
            System.out.println("已连接");
            String ip = socket.getInetAddress().getHostAddress();
            System.out.println("有客户端连接ip:" + ip + "端口:" + socket.getPort());
            String clientkey = ip + socket.getPort();
            CLENT_MAP.put(clientkey,socket);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            InputStream inputStream = socket.getInputStream();
                            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                            String readData = bufferedReader.readLine();
                            System.out.println("收到客户端"+ socket.getPort() +"消息->" + readData);


                            CLENT_MAP.forEach((k,v) ->{
                                try {
                                    OutputStream outputStream = v.getOutputStream();
                                    PrintWriter printWriter = new PrintWriter(outputStream);
                                    printWriter.println(socket.getPort() + ":" + readData);
                                    printWriter.flush();
                                }catch (Exception e){
                                    e.printStackTrace();
                                }
                            });
                        } catch (IOException e) {
                            e.printStackTrace();
                            break;
                        }
                    }
                }
            }).start();
        }
    }
}
